package system.service.sys.impl;

import framework.exceptions.BusinessException;
import lombok.Getter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import system.entity.SysState;
import system.mapper.SysStateMapper;
import system.service.sys.SysStateService;

import java.util.Date;

@Service
public class SysStateServiceImpl implements SysStateService {
    @Autowired
    @Getter
    private SysStateMapper mapper;

    @Override
    public int updateBody(SysState param) {
        return mapper.updateBody(param);
    }

    @Override
    public SysState loadState(String groupName, String name, String nodeName) {
        SysState state = new SysState();
        state.setGroupName(groupName);
        state.setName(name);
        state.setNodeName(nodeName);
        SysState s = mapper.one(state);
        if (s == null && !defaultNodeName().equals(nodeName)) {
            // 如果没有找到指定节点的状态，尝试查找全局状态
            state.setNodeName(defaultNodeName());
            s = mapper.one(state);
        }
        if (s != null && s.getExpireTime() != null) {
            // 如果过期时间不为null，且当前时间大于过期时间，则返回null
            if (s.getExpireTime().getTime() < System.currentTimeMillis()) {
                return null;
            }
        }
        return s;
    }

    @Override
    public Integer add(SysState param) {
        Date now = new Date();
        if (StringUtils.isBlank(param.getGroupName())) {
            param.setGroupName(defaultGroupName());
        }
        if (StringUtils.isBlank(param.getNodeName())) {
            param.setNodeName(defaultNodeName());
        }
        if (StringUtils.isBlank(param.getName())) {
            throw new BusinessException("State name cannot be empty");
        }
        if (param.getCreateTime() == null) {
            param.setCreateTime(now);
        }
        param.setUpdateTime(now);
        int rows = mapper.updateByName(param);
        if (rows == 0) {
            param.setCreateTime(now);
            rows = SysStateService.super.add(param);
        }
        return rows;
    }
}